import 'dart:async';

import 'package:demo/constants/bugly_key.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bugly/flutter_bugly.dart';

export 'package:flutter_bugly/flutter_bugly.dart' show UpgradeInfo;

/// 检查更新的回掉
typedef void OnCheckUpgradeListener(UpgradeInfo info);

class CrashAnalysisUtils {
  /// 工厂模式
  factory CrashAnalysisUtils() => _getInstance();

  /// 单例
  static CrashAnalysisUtils get instance => _getInstance();
  static CrashAnalysisUtils? _instance;

  CrashAnalysisUtils._internal();

  static CrashAnalysisUtils _getInstance() => _instance ??= CrashAnalysisUtils._internal();

  /// 监听的升级回掉
  StreamSubscription<UpgradeInfo>? _streamSubscription;

  /// 初始化bugly
  Future<void> initBugly() async {
    await FlutterBugly.init(
      androidAppId: BUGLY_ANDROID_APPID,
      iOSAppId: BUGLY_IOS_APPID,
      channel: BUGLY_CHANNEL_ID,
      // 不自动检查，手动在首页手动检查一次
      autoCheckUpgrade: false,
    );
  }

  /// 只设置一次全局升级的监听器
  /// 当配置 customUpgrade=true 时候，这里可以接收自定义升级
  void setOnCheckUpgradeListener(OnCheckUpgradeListener onCheckUpgradeListener) {
    if (_streamSubscription != null) {
      return;
    }
    _streamSubscription = FlutterBugly.onCheckUpgrade.listen(onCheckUpgradeListener);
  }

  ///自定义渠道标识 android专用
  Future<void> setAppChannel(String channel) async {
    await FlutterBugly.setAppChannel(channel);
  }

  /// 设置用户id
  Future<void> setUserId(String userId) async {
    await FlutterBugly.setUserId(userId);
  }

  /// 设置用户标签,标签ID，可在网站生成
  Future<void> setUserTag(int tag) async {
    await FlutterBugly.setUserTag(tag);
  }

  /// 设置关键数据，随崩溃信息上报
  Future<void> putUserData(String key, String value) async {
    await FlutterBugly.putUserData(key: key, value: value);
  }

  /// 设置关键数据，随崩溃信息上报
  Future<UpgradeInfo?> get getUpgradeInfo async {
    return await FlutterBugly.getUpgradeInfo();
  }

  /// 销毁
  void destroy() {
    if (_streamSubscription != null) {
      _streamSubscription!.cancel();
      _streamSubscription = null;
    }
    FlutterBugly.dispose();
  }

  /// 手动检查更新
  /// isUserClick 用户手动点击检查，非用户点击操作请传false
  /// isNeedWindowTips 是否显示弹窗等交互，[true:没有弹窗和toast] [false:有弹窗或toast]
  Future<void> checkUpgrade({bool isUserClick = false, bool isNeedWindowTips = false}) async {
    await FlutterBugly.checkUpgrade(isManual: isUserClick, isSilence: isNeedWindowTips);
  }

  /// 捕获flutter error比如对应的widget error
  static void catchFlutterError(FlutterErrorDetails details) {
    /// 生产环境直接进bugly上传直接转发沙箱内部去实现
    if (kReleaseMode) {
      StackTrace? stackTrace = details.stack;

      /// 可能没有stacktrace的问题，比如页面溢出
      if (stackTrace == null) {
        stackTrace = StackTrace.fromString(details.toString());
      }

      Zone.current.handleUncaughtError(details.exception, stackTrace);
      return;
    }
    FlutterError.dumpErrorToConsole(details);
  }

  /// 捕获flutter Isolate下的异常
  static void catchFlutterIsolateError(dynamic pair) {
    final List<dynamic> isolateError = pair as List<dynamic>;
    // 直接转发沙箱内部去实现
    Zone.current.handleUncaughtError(isolateError.first, isolateError.last);
  }

  /// 捕获flutter zone哨兵下的异常
  static void catchZonedGuardedError(dynamic error, StackTrace stackTrace) {
    // 生产环境直接进bugly上传
    if (kReleaseMode) {
      FlutterBugly.uploadException(message: error.toString(), detail: stackTrace.toString());
      return;
    }
    FlutterError.dumpErrorToConsole(FlutterErrorDetails(exception: error, stack: stackTrace));
  }
}
